package com.ckr.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ckr.common.lang.Result;
import com.ckr.entity.Blog;
import com.ckr.service.BlogService;
import com.ckr.util.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 * 博客前端控制器
 * </p>
 *
 * @author ShadowCkr
 * @since 2022-02-05
 */
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    BlogService blogService;

    /**
     * 按创建时间排序，分页查询所有博客
     */
    @GetMapping("/blogs")
    public Result getBlogList(@RequestParam(defaultValue = "1") Integer currentPage) {
        Page<Blog> page = new Page<>(currentPage, 5);
        QueryWrapper<Blog> wrapper = new QueryWrapper<>();
        QueryWrapper<Blog> queryWrapper = wrapper.orderByDesc("created");
        IPage<Blog> pageData = blogService.page(page, queryWrapper);

        return Result.success(pageData);
    }

    /**
     * 根据id查询具体的一篇博客信息
     */
    @GetMapping("/detail/{id}")
    public Result getBlogDetail(@PathVariable Long id) {
        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客已被删除！");
        return Result.success(blog);
    }

    /**
     * 根据id编辑博客，有id编辑，没有id则添加
     * 需要认证之后才能操作
     */
    @RequiresAuthentication
    @PostMapping("/edit")
    public Result edit(@Validated @RequestBody Blog blog) {
        Blog temp = null;
        // 编辑
        if (blog.getId() != null) {
            // 将要编辑的博客信息从数据库中查出并传递给temp
            temp = blogService.getById(blog.getId());
            // 只能编辑自己的文章（user_id）
            Assert.isTrue(temp.getUserId().longValue() == ShiroUtil.getProfile().getId().longValue(), "没有编辑权限！");
        } else {
            // 添加
            temp = new Blog();
            temp.setUserId(ShiroUtil.getProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }
        // 将blog的值赋给temp，忽略id，userId，created，status（hutool dependency）
        BeanUtil.copyProperties(blog, temp, "id", "userId", "created", "status");
        blogService.saveOrUpdate(temp);

        return Result.success("编辑成功！");
    }

    /**
     * 删除博客
     * 需要认证之后才能操作
     */
    @RequiresAuthentication
    @PostMapping("/delete/{id}")
    public Result deleteBlogById(@PathVariable Long id) {
        boolean remove = blogService.removeById(id);
        if (remove) {
            return Result.success("博客删除成功！");
        } else {
            return Result.fail("博客删除失败！");
        }
    }

}
